package com.qunar.train.mock.util;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;

/**
 * @author: xudong.tai
 * @since: 2018/7/11 Description: Generate object form data.properties
 **/
public class GenerateObjectFromData {
    public static final String data = "data.properties";

    //这种方式有2个缺陷: 1,生成Map耗时；2，Properties的load方法会去除转义字符导致json格式异常
    @Deprecated
    public static <T> T getObject_old(Class<T> clazz) {
        try {
            Map<String, String> map = ConfigHandle.loadConfig(data);
            for (String key : map.keySet()) {
                if (key.compareTo(clazz.getName()) == 0) {
                    T obj = JSON.parseObject(map.get(key), clazz);
                    //JsonMapper mapper = JsonMapper.buildNormalMapper();
                    //Object obj = mapper.fromJson(map.get(key), clazz);
                    return obj;
                }
            }
        } catch (Exception e) {
            AegisLog.error(e);
            return null;
        }
        AegisLog.error("Sorry, we can't find " + clazz.getName() + " in data.properties, please check!");
        return null;
    }

    public static <T> T getObject(Class<T> clazz) {
        try {
            String str = findConfig(data, clazz);
            if (str.equals("")) {
                AegisLog.error("Sorry, we can't find " + clazz.getName() + " in data.properties, please check!");
                return null;
            } else {
                //String value = str.split("=")[1].trim();
                String value = str.substring(str.indexOf("=") + 1);
                char[] charArray = value.toCharArray();
                StringBuilder res = new StringBuilder();
                int count = 0;
                //对转义符做下处理（这种模式下只有奇数个反斜杠才是标准json格式）
                for (int i = 0; i < charArray.length; i++) {
                    if (charArray[i] == '\\') {
                        count++;
                    } else {
                        if (count % 2 == 0 && count != 0) {
                            while (count-- > 1) res.append('\\');
                        } else if (count % 2 == 1 && count != 0) {
                            while (count-- > 0) res.append('\\');
                        }
                        res.append(charArray[i]);
                        count = 0;
                    }
                }
                value = res.toString();
                T obj = JSON.parseObject(value, clazz);
                return obj;
            }
        } catch (Exception e) {
            AegisLog.error(e);
            return null;
        }
    }

    private static String findConfig(String propertiesFile, Class clazz) {
        String path = Thread.currentThread().getContextClassLoader().getResource(propertiesFile).getPath();
        File file = new File(path);
        String result = "";
        if (!file.exists()) {    // 判断文件是否存在
            AegisLog.info("文件不存在");
            return result;
        } else if (file.isDirectory()) {
            AegisLog.info("这不是一个文件，而是一个目录");
            return result;
        } else {
            BufferedReader reader = null;
            try {
                //AegisLog.info("以行为单位读取文件内容，一次读一整行：");
                reader = new BufferedReader(new FileReader(file));
                String tempString = null;
                while ((tempString = reader.readLine()) != null) {
                    if (tempString.split("=")[0].trim().compareTo(clazz.getName()) == 0) {
                        result = tempString.trim();
                    }
                }
                reader.close();
            } catch (IOException e) {
                AegisLog.error(e);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e1) {
                        AegisLog.error(e1);
                    }
                }
                return result;
            }
        }
    }

}
